const mongoose = require("mongoose");
const fs = require("fs");
const xlsx = require("node-xlsx");
const UserQues = require("../models/UserQuesModel");
const QuesSpeed = require("../models/QuesSpeedModel");
const Opinion = require("../models/OpinionModel");
const FileData = require("../models/FileDataModel");
const UserProblem = require("../models/UserProModel");

const QuesTemplate = require("../models/QuesModel");
const Provinces = require("../models/provincesModel");
const Cities = require("../models/citiesModel");
const Areas = require("../models/areasModel");
const Streets = require("../models/streetsModel");
const Villages = require("../models/villagesModel");

const excelFun = require("../util/excelFun");

exports.addUserQues = async (req, res) => {
  try {
    let req_data = req.body;
    if (req_data.target == 5) {
      // console.log("一般户");
      let i;
      for (i = 6; i < 13; i++) {
        if (req_data.body[1].contents[6].answer != 1) {
          break;
        }
      }
      if (i == 14) {
        req_data.target = 6;
        // console.log("长");
      } else {
        req_data.target = 5;
        // console.log("短");
      }
    }
    // console.log(req_data.target);
    // console.log("开始添加");
    const newUserQues = await UserQues.create(req_data);
    let logStr =
      "\n添加问卷完成---title：" +
      newUserQues.title +
      "---state：" +
      newUserQues.state +
      "---target：" +
      newUserQues.target;
    fs.writeFile("./recordLog.text", logStr, { flag: "a+" }, (err) => {
      if (err) {
        return console.log("文件写入失败", err.message);
      }
      console.log("写入成功---", logStr);
    });
    res.status(201).json({
      status: "success",
      data: newUserQues,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.getUserQues = async (req, res) => {
  try {
    const UserQuesData = await UserQues.find()
      .sort({ time: -1 })
      .populate("user")
      .populate("userproblem")
      .populate("opinions")
      .populate("filedata");
    res.status(201).json({
      status: "success",
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.getUserQuesPage = async (req, res) => {
  try {
    // console.log("开始查");
    const page = Number(req.query.page);
    const pageSize = Number(req.query.pageSize);

    const length = await UserQues.find().count();
    const UserQuesData = await UserQues.find()
      .sort({ time: -1 })
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .populate("user")
      .populate("userproblem")
      .populate("opinions")
      .populate("filedata");
    res.status(201).json({
      status: "success",
      dataLen: length,
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.getUserQuesById = async (req, res) => {
  const id = req.params.id;
  console.log(id);
  try {
    const UserQuesData = await UserQues.findOne({ _id: id })
      .sort({ time: -1 })
      .populate("user")
      .populate("userproblem")
      .populate("opinions")
      .populate("filedata");
    res.status(201).json({
      status: "success",
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.getUserQuesByGroupId = async (req, res) => {
  const group = req.params.id;
  // console.log("组---", group);
  try {
    let UserQuesData;
    if (group == "-1") {
      UserQuesData = await UserQues.find({ state: [1, 2, 3] })
        .sort({ time: -1 })
        .populate("user")
        .populate("userproblem")
        .populate("opinions")
        .populate("filedata");
    } else {
      UserQuesData = await UserQues.find({ group: group, state: [1, 2, 3] })
        .sort({ time: -1 })
        .populate("user")
        .populate("userproblem")
        .populate("opinions")
        .populate("filedata");
    }

    res.status(201).json({
      status: "success",
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.getUserQuesByGroupIdPage = async (req, res) => {
  const group = req.params.id;
  // console.log("组---", group);
  try {
    const page = Number(req.query.page);
    const pageSize = Number(req.query.pageSize);
    let UserQuesData;
    let length;
    if (group == "-1") {
      length = await UserQues.find({ state: [1, 2, 3] }).count();
      UserQuesData = await UserQues.find({ state: [1, 2, 3] })
        .sort({ time: -1 })
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .populate("user")
        .populate("userproblem")
        .populate("opinions")
        .populate("filedata");
    } else {
      length = await UserQues.find({ group: group, state: [1, 2, 3] }).count();
      UserQuesData = await UserQues.find({ group: group, state: [1, 2, 3] })
        .sort({ time: -1 })
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .populate("user")
        .populate("userproblem")
        .populate("opinions")
        .populate("filedata");
    }

    res.status(201).json({
      status: "success",
      dataLen: length,
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.getUserQuesByUserId = async (req, res) => {
  const u_id = req.params.id;
  // console.log("查找---", u_id);
  try {
    const UserQuesData = await UserQues.find(
      { user: u_id }
      // { sort: [["_id", -1]] }
    )
      .sort({ time: -1 })
      .populate("user")
      .populate("userproblem")
      .populate("opinions")
      .populate("filedata");
    // for(let i = 0; i++;)
    // console.log(UserQuesData);
    res.status(201).json({
      status: "success",
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.getUserQuesByUserIdPage = async (req, res) => {
  const u_id = req.params.id;
  // console.log("查找---", u_id);
  try {
    const page = Number(req.query.page);
    const pageSize = Number(req.query.pageSize);
    const length = await UserQues.find({ user: u_id }).count();
    const UserQuesData = await UserQues.find({ user: u_id })
      .sort({ time: -1 })
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .populate("user")
      .populate("userproblem")
      .populate("opinions")
      .populate("filedata");
    // for(let i = 0; i++;)
    // console.log(UserQuesData);
    res.status(201).json({
      status: "success",
      dataLen: length,
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.updateUserQues = async (req, res) => {
  try {
    let req_data = req.body.Ques;
    if (req_data.target == 5) {
      // console.log("一般户");
      let i;
      for (i = 6; i <= 13; i++) {
        if (req_data.body[1].contents[i].answer != 1) {
          break;
        }
      }
      if (i == 14) {
        req_data.target = 6;
        // console.log("短");
      } else {
        req_data.target = 5;
        // console.log("长");
      }
    }
    let oldUserQues = await UserQues.findOne({ _id: req_data._id });
    let oldState = oldUserQues.state;
    let newState = req_data.state;
    req_data.user = oldUserQues.user;
    // console.log("新旧状态---", newState, oldState);
    const UserQuesData = await UserQues.updateOne(
      { _id: req_data._id },
      req_data
    );
    let flag = req.body.flag;
    let logStr =
      "\n更新问卷完成---title：" +
      req_data.title +
      "---state：" +
      req_data.state +
      "---target：" +
      req_data.target;
    fs.writeFile("./recordLog.text", logStr, { flag: "a+" }, (err) => {
      if (err) {
        return console.log("文件写入失败", err.message);
      }
      console.log("写入成功---", logStr);
    });
    if (flag == "upload" && oldState == 0 && newState == 1) {
      let Ques = req_data;
      // console.log(Ques);
      // let province = await Provinces.findOne({
      //   code: Ques.body[0].contents[0].title[0].answer,
      // });
      // province = province.name;
      let city = await Cities.findOne({
        code: Ques.body[0].contents[0].title[0].answer[0],
      });
      city = city.name;
      let country = await Areas.findOne({
        code: Ques.body[0].contents[0].title[0].answer[1],
      });
      country = country.name;
      let town = await Streets.findOne({
        code: Ques.body[0].contents[0].title[0].answer[2],
      });
      town = town.name;
      let village;
      if (Ques.body[0].contents[0].title[4].answer == "***") {
        village = await Villages.findOne({
          code: Ques.body[0].contents[0].title[0].answer[3],
        });
        village = village.name;
      } else {
        village = Ques.body[0].contents[0].title[4].answer;
      }

      let s_time = new Date(Ques.time);
      s_time =
        "" + s_time.getFullYear() + (s_time.getMonth() + 1) + s_time.getDate();
      let adress1 = city + country + town + village + s_time;
      let adress2 = city + s_time;
      let group = Ques.group;
      let attribute =
        Ques.body[0].contents[2].options[Ques.body[0].contents[2].answer];
      let target = req_data.target;
      console.log(
        oldUserQues.group,
        "---",
        target,
        "---",
        city,
        country,
        town,
        village,
        "---",
        attribute
      );

      // 调研员精确到市
      const template_contents = await QuesSpeed.find({
        adress: adress2,
      });
      // console.log(template_contents);
      if (template_contents == null || template_contents.length == 0) {
        let tuopinhu = [0, 0, 0];
        let bianyuanhu = [0, 0];
        let yibanhu = [0, 0];
        if (target == 0) {
          tuopinhu[0]++;
        } else if (target == 1) {
          tuopinhu[2]++;
        } else if (target == 2) {
          tuopinhu[1]++;
        } else if (target == 3) {
          bianyuanhu[1]++;
        } else if (target == 4) {
          bianyuanhu[0]++;
        } else if (target == 5) {
          yibanhu[0]++;
        } else if (target == 6) {
          yibanhu[1]++;
        }
        let NewSpeedData = {
          adress: adress2,
          province: "陕西省",
          city: city,
          country: "",
          town: "",
          village: "",
          attribute: "",
          group: -1,
          time: new Date(),
          tuopinhu: tuopinhu,
          bianyuanhu: bianyuanhu,
          yibanhu: yibanhu,
        };
        const newSpeed = await QuesSpeed.create(NewSpeedData);
        console.log("创建审核员新调研进度成功---", newSpeed);
      } else {
        let data1 = template_contents[0];
        if (target == 0) {
          data1.tuopinhu[0]++;
        } else if (target == 1) {
          data1.tuopinhu[2]++;
        } else if (target == 2) {
          data1.tuopinhu[1]++;
        } else if (target == 3) {
          data1.bianyuanhu[1]++;
        } else if (target == 4) {
          data1.bianyuanhu[0]++;
        } else if (target == 5) {
          data1.yibanhu[0]++;
        } else if (target == 6) {
          data1.yibanhu[1]++;
        }
        const res_data1 = await QuesSpeed.updateOne({ _id: data1._id }, data1);
        console.log("更新审核员问卷进度成功---");
      }

      // 管理员精确到村
      const template_contents1 = await QuesSpeed.find({
        adress: adress1,
      });
      // console.log(template_contents1);
      if (template_contents1 == null || template_contents1.length == 0) {
        let tuopinhu = [0, 0, 0];
        let bianyuanhu = [0, 0];
        let yibanhu = [0, 0];
        if (target == 0) {
          tuopinhu[0]++;
        } else if (target == 1) {
          tuopinhu[2]++;
        } else if (target == 2) {
          tuopinhu[1]++;
        } else if (target == 3) {
          bianyuanhu[1]++;
        } else if (target == 4) {
          bianyuanhu[0]++;
        } else if (target == 5) {
          yibanhu[0]++;
        } else if (target == 6) {
          yibanhu[1]++;
        }
        let NewSpeedData = {
          adress: adress1,
          province: "陕西省",
          city: city,
          country: country,
          town: town,
          village: village,
          attribute: attribute,
          group: oldUserQues.group,
          time: new Date(),
          tuopinhu: tuopinhu,
          bianyuanhu: bianyuanhu,
          yibanhu: yibanhu,
        };
        const newGroupSpeed = await QuesSpeed.create(NewSpeedData);
        console.log("创建管理员新调研进度成功---", newGroupSpeed);
      } else {
        let data1 = template_contents1[0];
        if (target == 0) {
          data1.tuopinhu[0]++;
        } else if (target == 1) {
          data1.tuopinhu[2]++;
        } else if (target == 2) {
          data1.tuopinhu[1]++;
        } else if (target == 3) {
          data1.bianyuanhu[1]++;
        } else if (target == 4) {
          data1.bianyuanhu[0]++;
        } else if (target == 5) {
          data1.yibanhu[0]++;
        } else if (target == 6) {
          data1.yibanhu[1]++;
        }
        const res_data1 = await QuesSpeed.updateOne({ _id: data1._id }, data1);
        console.log("更新管理员问卷进度成功---");
      }
    }

    res.status(201).json({
      status: "success",
      data: UserQuesData,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      status: true,
      err,
    });
  }
};

exports.deleteUserQues = async (req, res) => {
  // console.log("query---", req.query);
  // console.log("body---", req.body);
  // console.log("params---", req.params);
  try {
    const ques_id = mongoose.Types.ObjectId(req.query.ques_id);
    const opinion_id = mongoose.Types.ObjectId(req.query.opinion_id);
    const filedata_id = mongoose.Types.ObjectId(req.query.opinion_id);
    const problem_id = mongoose.Types.ObjectId(req.query.problem_id);

    const before_data = await UserQues.findOne({ _id: ques_id });
    const ques_data = await UserQues.deleteOne({ _id: ques_id });
    let logStr = "\n删除问卷成功---title：" + before_data.title;
    fs.writeFile("./recordLog.text", logStr, { flag: "a+" }, (err) => {
      if (err) {
        return console.log("文件写入失败", err.message);
      }
      console.log("写入成功---", logStr);
    });
    const filedata_data = await FileData.deleteOne({ _id: filedata_id });
    const problem_data = await UserProblem.deleteOne({ _id: problem_id });
    const opinion_data = await Opinion.deleteOne({ _id: opinion_id });
    res.status(200).json({
      status: "success",
      data: {
        ques_data,
        filedata_data,
        problem_data,
        opinion_data,
      },
    });
  } catch (err) {
    console.log("删除问卷失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

exports.getExcelData = async (req, res) => {
  const idArr = req.query.idArr;
  console.log("idArr---", idArr);
  let ExcelData = [
    [[], []],
    [[], []],
    [[], []],
    [[], []],
    [[], []],
    [[], []],
  ];
  let count = [0, 0, 0, 0, 0, 0];

  let UserQuesData = [];
  for (let i = 0; i < idArr.length; i++) {
    let data = await UserQues.findOne({ _id: idArr[i] });
    UserQuesData.push(data);
    console.log("问卷类型---", data.target);
    if (data.target < 5) {
      ExcelData[data.target].push([]);
    } else if (data.target == 5 || data.target == 6) {
      ExcelData[5].push([]);
    }
  }

  try {
    for (let i = 0; i < UserQuesData.length; i++) {
      let num;
      if (UserQuesData[i].target < 5) {
        num = UserQuesData[i].target;
      } else if (UserQuesData[i].target == 5 || UserQuesData[i].target == 6) {
        num = 5;
      }
      count[num]++;
      if (count[num] == 1) {
        ExcelData[num][0].push("ID");
        ExcelData[num][1].push("问卷编号");
      }
      ExcelData[num][count[num] + 1].push(UserQuesData[i].title);
      for (let j = 0; j < UserQuesData[i].body.length; j++) {
        for (let k = 0; k < UserQuesData[i].body[j].contents.length; k++) {
          let t_content = UserQuesData[i].body[j].contents[k];

          if (t_content.type == 5) {
            for (let l = 0; l < t_content.title.length; l++) {
              let t_title = t_content.title[l];

              if (t_title.type == 6) {
                if (count[num] == 1 && t_title.type != -1) {
                  ExcelData[num][0].push("A1a");
                  ExcelData[num][0].push("A1b");
                  ExcelData[num][0].push("A1c");
                  ExcelData[num][0].push("A1d");
                  ExcelData[num][1].push("市");
                  ExcelData[num][1].push("县");
                  ExcelData[num][1].push("乡（镇）");
                  ExcelData[num][1].push("行政村（社区）");
                }
                let city = await Cities.findOne({
                  code: t_title.answer[0],
                });
                ExcelData[num][count[num] + 1].push(city.name);
                let country = await Areas.findOne({
                  code: t_title.answer[1],
                });
                ExcelData[num][count[num] + 1].push(country.name);
                let town = await Streets.findOne({
                  code: t_title.answer[2],
                });
                ExcelData[num][count[num] + 1].push(town.name);
                let village = "***";
                if (t_title.answer[3] != "") {
                  village = await Villages.findOne({
                    code: t_title.answer[3],
                  });
                  village = village.name;
                }
                ExcelData[num][count[num] + 1].push(village);
              } else {
                let number =
                  String.fromCharCode(j + 65) +
                  (k + 1) +
                  String.fromCharCode(l + 97);
                if (count[num] == 1 && t_title.type != -1) {
                  ExcelData[num][0].push(number);
                  ExcelData[num][1].push(t_title.title);
                }
                if (t_title.type == 1 || t_title.type == 7) {
                  if (t_title.answer == "" || !t_title.visible) {
                    ExcelData[num][count[num] + 1].push("***");
                  } else {
                    ExcelData[num][count[num] + 1].push(t_title.answer);
                  }
                } else if (t_title.type == 2) {
                  let answer = t_title.answer;
                  if (answer != -1 && t_title.visible) {
                    if (t_title.optionFlag[answer][0]) {
                      ExcelData[num][count[num] + 1].push(
                        "[" +
                          (answer + 1) +
                          "]" +
                          t_title.options[answer] +
                          "; " +
                          t_title.optionFlag[answer][1]
                      );
                    } else {
                      ExcelData[num][count[num] + 1].push(
                        "[" + (answer + 1) + "]" + t_title.options[answer]
                      );
                    }
                  } else {
                    ExcelData[num][count[num] + 1].push("***");
                  }
                } else if (t_title.type == 3) {
                  let result = "";
                  let answer = t_title.answer;
                  for (let p = 0; p < answer.length; p++) {
                    if (answer[p]) {
                      if (t_title.optionFlag[p][0]) {
                        result =
                          result +
                          "[" +
                          (p + 1) +
                          "]" +
                          t_title.options[p] +
                          "; " +
                          t_title.optionFlag[p][1];
                        ("\n");
                      } else {
                        result =
                          result +
                          "[" +
                          (p + 1) +
                          "]" +
                          t_title.options[p] +
                          "\n";
                      }
                    }
                  }
                  if (result == "" || !t_title.visible) {
                    result = "***";
                  }
                  ExcelData[num][count[num] + 1].push(result);
                }
              }
            }
          } else {
            if (count[num] == 1 && t_content.type != -1) {
              ExcelData[num][0].push(String.fromCharCode(j + 65) + (k + 1));
              ExcelData[num][1].push(t_content.title);
            }
            if (t_content.type == 1 || t_content.type == 7) {
              if (t_content.answer != "" && t_content.visible) {
                ExcelData[num][count[num] + 1].push(t_content.answer);
              } else {
                ExcelData[num][count[num] + 1].push("***");
              }
            } else if (t_content.type == 2) {
              let answer = t_content.answer;
              if (answer != -1 && t_content.visible) {
                if (t_content.optionFlag[answer][0]) {
                  ExcelData[num][count[num] + 1].push(
                    "[" +
                      (answer + 1) +
                      "]" +
                      t_content.options[answer] +
                      "; " +
                      t_content.optionFlag[answer][1]
                  );
                } else {
                  ExcelData[num][count[num] + 1].push(
                    "[" + (answer + 1) + "]" + t_content.options[answer]
                  );
                }
              } else {
                ExcelData[num][count[num] + 1].push("***");
              }
            } else if (t_content.type == 3) {
              let result = "";
              let answer = t_content.answer;
              for (let p = 0; p < answer.length; p++) {
                if (answer[p]) {
                  if (t_content.optionFlag[p][0]) {
                    result =
                      result +
                      "[" +
                      (p + 1) +
                      "]" +
                      t_content.options[p] +
                      "; " +
                      t_content.optionFlag[p][1] +
                      "\n";
                  } else {
                    result =
                      result +
                      "[" +
                      (p + 1) +
                      "]" +
                      t_content.options[p] +
                      "\n";
                  }
                }
              }
              if (result == "" || !t_content.visible) {
                result = "***";
              }
              ExcelData[num][count[num] + 1].push(result);
            }
          }
        }
      }
    }
    res.status(201).json({
      status: "success",
      data: ExcelData,
    });
  } catch (error) {
    console.log(error);
    res.status(404).json({
      status: true,
      error,
    });
  }
};

exports.generateExcelData = async (req, res) => {
  try {
    excelFun.generateExcelDataFun(req.params.id);
    res.status(201).json({
      status: "success",
      data: "在处理了",
    });
  } catch (error) {
    console.log(error);
    res.status(404).json({
      status: true,
      error,
    });
  }
};

// exports.generateExcelData = async (req, res) => {
//   try {
//     console.log("1");
//     const group = req.params.id;
//     console.log("group---", group);
//     console.log("2");

//     let ExcelData = [
//       [[], []],
//       [[], []],
//       [[], []],
//       [[], []],
//       [[], []],
//       [[], []],
//     ];
//     let count = [0, 0, 0, 0, 0, 0];
//     console.log("3");

//     let UserQuesData = [];
//     if (group == "-1") {
//       console.log("4");
//       UserQuesData = await UserQues.find({ state: [1, 2, 3] });
//     } else {
//       console.log("5");
//       UserQuesData = await UserQues.find({ group: group, state: [1, 2, 3] });
//     }
//     console.log("6");

//     for (let i = 0; i < UserQuesData.length; i++) {
//       console.log("问卷类型---", i, "--", UserQuesData[i].target);
//       if (UserQuesData[i].target < 5) {
//         ExcelData[UserQuesData[i].target].push([]);
//       } else if (UserQuesData[i].target == 5 || UserQuesData[i].target == 6) {
//         ExcelData[5].push([]);
//       }
//     }
//     console.log("7");

//     // fs.unlink("./exceldata/" + group + ".xlsx", (err) => {
//     //   if (err) {
//     //     console.log("删除失败---", err);
//     //   } else {
//     //     console.log("删除成功");
//     //   }
//     // });
//     console.log("8");
//     for (let i = 0; i < UserQuesData.length; i++) {
//       console.log(i);
//       let num;
//       if (UserQuesData[i].target < 5) {
//         num = UserQuesData[i].target;
//       } else if (UserQuesData[i].target == 5 || UserQuesData[i].target == 6) {
//         num = 5;
//       }
//       count[num]++;
//       if (count[num] == 1) {
//         ExcelData[num][0].push("ID");
//         ExcelData[num][1].push("问卷编号");
//       }
//       ExcelData[num][count[num] + 1].push(UserQuesData[i].title);
//       for (let j = 0; j < UserQuesData[i].body.length; j++) {
//         for (let k = 0; k < UserQuesData[i].body[j].contents.length; k++) {
//           let t_content = UserQuesData[i].body[j].contents[k];

//           if (t_content.type == 5) {
//             for (let l = 0; l < t_content.title.length; l++) {
//               let t_title = t_content.title[l];

//               if (t_title.type == 6) {
//                 if (count[num] == 1 && t_title.type != -1) {
//                   ExcelData[num][0].push("A1a");
//                   ExcelData[num][0].push("A1b");
//                   ExcelData[num][0].push("A1c");
//                   ExcelData[num][0].push("A1d");
//                   ExcelData[num][1].push("市");
//                   ExcelData[num][1].push("县");
//                   ExcelData[num][1].push("乡（镇）");
//                   ExcelData[num][1].push("行政村（社区）");
//                 }
//                 let city = await Cities.findOne({
//                   code: t_title.answer[0],
//                 });
//                 ExcelData[num][count[num] + 1].push(city.name);
//                 let country = await Areas.findOne({
//                   code: t_title.answer[1],
//                 });
//                 ExcelData[num][count[num] + 1].push(country.name);
//                 let town = await Streets.findOne({
//                   code: t_title.answer[2],
//                 });
//                 ExcelData[num][count[num] + 1].push(town.name);
//                 let village = "***";
//                 if (t_title.answer[3] != "") {
//                   village = await Villages.findOne({
//                     code: t_title.answer[3],
//                   });
//                   village = village.name;
//                 }
//                 ExcelData[num][count[num] + 1].push(village);
//               } else {
//                 let number =
//                   String.fromCharCode(j + 65) +
//                   (k + 1) +
//                   String.fromCharCode(l + 97);
//                 if (count[num] == 1 && t_title.type != -1) {
//                   ExcelData[num][0].push(number);
//                   ExcelData[num][1].push(t_title.title);
//                 }
//                 if (t_title.type == 1 || t_title.type == 7) {
//                   if (t_title.answer == "" || !t_title.visible) {
//                     ExcelData[num][count[num] + 1].push("***");
//                   } else {
//                     ExcelData[num][count[num] + 1].push(t_title.answer);
//                   }
//                 } else if (t_title.type == 2) {
//                   let answer = t_title.answer;
//                   if (answer != -1 && t_title.visible) {
//                     if (t_title.optionFlag[answer][0]) {
//                       ExcelData[num][count[num] + 1].push(
//                         "[" +
//                           (answer + 1) +
//                           "]" +
//                           t_title.options[answer] +
//                           "; " +
//                           t_title.optionFlag[answer][1]
//                       );
//                     } else {
//                       ExcelData[num][count[num] + 1].push(
//                         "[" + (answer + 1) + "]" + t_title.options[answer]
//                       );
//                     }
//                   } else {
//                     ExcelData[num][count[num] + 1].push("***");
//                   }
//                 } else if (t_title.type == 3) {
//                   let result = "";
//                   let answer = t_title.answer;
//                   for (let p = 0; p < answer.length; p++) {
//                     if (answer[p]) {
//                       if (t_title.optionFlag[p][0]) {
//                         result =
//                           result +
//                           "[" +
//                           (p + 1) +
//                           "]" +
//                           t_title.options[p] +
//                           "; " +
//                           t_title.optionFlag[p][1];
//                         ("\n");
//                       } else {
//                         result =
//                           result +
//                           "[" +
//                           (p + 1) +
//                           "]" +
//                           t_title.options[p] +
//                           "\n";
//                       }
//                     }
//                   }
//                   if (result == "" || !t_title.visible) {
//                     result = "***";
//                   }
//                   ExcelData[num][count[num] + 1].push(result);
//                 }
//               }
//             }
//           } else {
//             if (count[num] == 1 && t_content.type != -1) {
//               ExcelData[num][0].push(String.fromCharCode(j + 65) + (k + 1));
//               ExcelData[num][1].push(t_content.title);
//             }
//             if (t_content.type == 1 || t_content.type == 7) {
//               if (t_content.answer != "" && t_content.visible) {
//                 ExcelData[num][count[num] + 1].push(t_content.answer);
//               } else {
//                 ExcelData[num][count[num] + 1].push("***");
//               }
//             } else if (t_content.type == 2) {
//               let answer = t_content.answer;
//               if (answer != -1 && t_content.visible) {
//                 if (t_content.optionFlag[answer][0]) {
//                   ExcelData[num][count[num] + 1].push(
//                     "[" +
//                       (answer + 1) +
//                       "]" +
//                       t_content.options[answer] +
//                       "; " +
//                       t_content.optionFlag[answer][1]
//                   );
//                 } else {
//                   ExcelData[num][count[num] + 1].push(
//                     "[" + (answer + 1) + "]" + t_content.options[answer]
//                   );
//                 }
//               } else {
//                 ExcelData[num][count[num] + 1].push("***");
//               }
//             } else if (t_content.type == 3) {
//               let result = "";
//               let answer = t_content.answer;
//               for (let p = 0; p < answer.length; p++) {
//                 if (answer[p]) {
//                   if (t_content.optionFlag[p][0]) {
//                     result =
//                       result +
//                       "[" +
//                       (p + 1) +
//                       "]" +
//                       t_content.options[p] +
//                       "; " +
//                       t_content.optionFlag[p][1] +
//                       "\n";
//                   } else {
//                     result =
//                       result +
//                       "[" +
//                       (p + 1) +
//                       "]" +
//                       t_content.options[p] +
//                       "\n";
//                   }
//                 }
//               }
//               if (result == "" || !t_content.visible) {
//                 result = "***";
//               }
//               ExcelData[num][count[num] + 1].push(result);
//             }
//           }
//         }
//       }
//     }
//     console.log("9");
//     const typeOptions = [
//       "脱贫稳定户",
//       "脱贫不稳定户",
//       "突发困难严重户1",
//       "突发困难严重户2",
//       "边缘易致贫户",
//       "其他户",
//       "全部",
//     ];
//     console.log("10");
//     const list = [];
//     for (let i = 0; i < ExcelData.length; i++) {
//       if (ExcelData[i].length > 2) {
//         let list_content = {
//           name: typeOptions[i],
//           data: ExcelData[i],
//         };
//         list.push(list_content);
//       }
//     }

//     console.log("11");
//     const buffer = xlsx.build(list);
//     let newdate = new Date();
//     let time =
//       newdate.getFullYear() + (newdate.getMonth + 1) + newdate.getDay();
//     fs.writeFile("./exceldata/" + group + time + ".xlsx", buffer, (error) => {
//       if (error) {
//         console.log("导出excel失败---", group, "---", error);
//         console.log(error);
//         res.status(404).json({
//           status: true,
//           error,
//         });
//       } else {
//         console.log("成功");
//         let ExcelUri = "http://192.168.137.1:3000/exceldata/" + group + ".xlsx";
//         console.log("地址---", ExcelUri);
//         res.status(201).json({
//           status: "success",
//           data: ExcelUri,
//         });
//       }
//     });
//     // console.log("成功出来了");
//     // let ExcelUri =
//     //   "http://1468-240c-c28f-1020-ed68-a471-24ac-1ab9-ff2c.ngrok.io/exceldata/" +
//     //   group +
//     //   ".xlsx";
//     // console.log("地址---", ExcelUri);
//     // res.status(201).json({
//     //   status: "success",
//     //   data: ExcelUri,
//     // });
//   } catch (error) {
//     console.log(error);
//     res.status(404).json({
//       status: true,
//       error,
//     });
//   }
// };
